package com.custom.base.base

import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast

import androidx.recyclerview.widget.RecyclerView
import com.github.jdsjlzx.util.SuperViewHolder

import com.custom.base.R
import com.custom.base.manager.SDSelectManager
import com.custom.base.type.AnimationActivityType
import com.custom.base.util.IntentUtil

import java.util.ArrayList

/**
 * 封装adapter
 * */
abstract class BaseRecyclerContextAdapter<T>(
    listModel: ArrayList<T>,
    protected var mActivity: Context
) : RecyclerView.Adapter<SuperViewHolder>() {
    private var mToast: Toast? = null
    private val mHandler = Handler(Looper.getMainLooper())

    /**
     * show Toast
     */
    private val mShowToastRunnable = Runnable { mToast?.show() }

    private val mInflater: LayoutInflater

    protected var mDataList: ArrayList<T> = ArrayList()

    abstract val layoutId: Int

    /**
     * 选择器
     */
    val mSelectManager: SDSelectManager<T> =
        SDSelectManager()
        get() = field

    /**
     * 点击回调
     */
    private var mListenerItemClick: ItemClickListener<T>? = null

    private val mListenerItemState: ItemStateListener<T>? = null

    var dataList: List<T>
        get() = mDataList
        set(list) {
            this.mDataList.addAll(list)
            mSelectManager.setItems(mDataList)
            notifyDataSetChanged()
        }

    init {
        mSelectManager.mMode = SDSelectManager.Mode.SINGLE
        /**
         * 默认选择管理器监听
         */
        mSelectManager.setListener(object : SDSelectManager.SDSelectManagerListener<T>{
            override fun onNormal(index: Int, item: T?) {
                onNormalItem(index, item)
                mListenerItemState?.onNormal(index, item)
            }

            override fun onSelected(index: Int, item: T?) {
                onSelectedItem(index, item)
                mListenerItemState?.onSelected(index, item)
            }
        })
        mSelectManager.setItems(listModel)
        mDataList = listModel
        mInflater = mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SuperViewHolder {
        val itemView = mInflater.inflate(layoutId, parent, false)
        //对于listview，注意添加这一行，即可在item上使用高度
        com.custom.base.util.AutoUtils.autoSize(itemView)
        return SuperViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: SuperViewHolder, position: Int) {
        onBindItemHolder(position, holder, dataList[position], null)
        mListenerItemClick?.apply {
            holder.setOnClickListener {
                mListenerItemClick?.onClick(position, dataList[position],holder)
            }
        }
    }

    override fun onBindViewHolder(
        holder: SuperViewHolder,
        position: Int,
        payloads: MutableList<Any>
    ) {
        onBindItemHolder(position, holder, dataList[position], payloads)
    }

    abstract fun onBindItemHolder(
        position: Int,
        holder: SuperViewHolder,
        model: T,
        payloads: List<Any>?
    )

    override fun getItemCount(): Int {
        return mDataList.size
    }

    fun addAll(list: List<T>) {
        val lastIndex = this.mDataList.size
        if (this.mDataList.addAll(list)) {
            notifyItemRangeInserted(lastIndex, list.size)
        }
    }

    fun add(t: T) {
        mDataList.add(t)
        notifyDataSetChanged()
    }

    /**
     * 删除
     */
    fun remove(position: Int) {
        mDataList.removeAt(position)
        notifyItemRemoved(position)

        if (position != dataList.size) { // 如果移除的是最后一个，忽略
            notifyItemRangeChanged(position, this.mDataList.size - position)
        }
    }
    /**
     * 删除
     */
    fun remove(t: T) {
        for (i in mDataList.indices) {
            if(t == mDataList[i]){
                remove(i)
                break
            }
        }
    }

    fun clear() {
        mDataList.clear()
        notifyDataSetChanged()
    }

    /**
     * 刷新position对应的itemView
     *
     * @param position
     */
    fun updateItem(position: Int) {
        notifyItemChanged(position)
    }

    /**
     * item被置为正常状态的时候回调
     *
     * @param position
     * @param item
     */
    protected open fun onNormalItem(position: Int, item: T?) {
        if (item is BaseSDAdapter.SDSelectable) {
            val selectable = item as BaseSDAdapter.SDSelectable
            selectable.isSelected = false
        }
        updateItem(position)
    }
    /**onEventMainThread
     * item被置为选中状态的时候回调
     *
     * @param position
     * @param item
     */
    protected open fun onSelectedItem(position: Int, item: T?) {
        if (item is BaseSDAdapter.SDSelectable) {
            val selectable = item as BaseSDAdapter.SDSelectable
            selectable.isSelected = true
        }
        updateItem(position)
    }

    /**
     * 将实体中的选中状态同步到选择管理器中，常用于设置数据后调用，只有实体实现了SDSelectable接口调用此方法才有效
     */
    private fun synchronizedSelected() {
        for (model in mDataList) {
            synchronizedSelected(model)
        }
    }

    private fun synchronizedSelected(model: T) {
        if (model is BaseSDAdapter.SDSelectable) {
            val sModel = model as BaseSDAdapter.SDSelectable
            if (mSelectManager.isSelected(model) != sModel.isSelected) {
                mSelectManager.setSelected(model, sModel.isSelected)
            }
        }
    }

    interface ItemStateListener<T> {
        fun onNormal(position: Int, item: T?)
        fun onSelected(position: Int, item: T?)
    }
    interface ItemClickListener<T> {
        fun onClick(position: Int, item: T, holder: SuperViewHolder)
    }
    /**
     * 设置回调
     */
    fun setListenerItemClick(listenerItemClick: ItemClickListener<T>) {
        this.mListenerItemClick = listenerItemClick
    }

    /**
     * 简化Toast
     */
    fun showToast(messageId: String,looper:Boolean = false) {
        if(looper) Looper.prepare()
        if (mToast == null) {
            mToast = Toast.makeText(mActivity, messageId, Toast.LENGTH_SHORT)
        }
        mToast?.setText(messageId)
        mToast?.cancel()
        mHandler.removeCallbacks(mShowToastRunnable)
        mHandler.postDelayed(mShowToastRunnable, 0)
        if(looper) Looper.loop()
    }
    /**
     * 页面跳转
     */
    fun startActivity(
        clz: Class<*>,
        bundle: Bundle? = null,
        view:View? = null,
        requestCode: Int = 0,
        flags: List<Int> = listOf(),
        animationStartType: AnimationActivityType = AnimationActivityType.RIGHT,
        animationEndType:Int = R.anim.animo_no
    ) {
        IntentUtil.startActivity(clz, bundle, requestCode, flags, view,animationStartType = animationStartType,animationEndType = animationEndType)
    }
}
